<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品</el-breadcrumb-item>
      <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col :span="6">
          <el-autocomplete
            v-model="pageReqParams.query"
            clearable
            @input="handleSearchBrandsButtonClick()"
            :fetch-suggestions="handleQuerySearchBrand"
            placeholder="搜索品牌" class="input-with-select"
            value-key="name"
            style="width: 300px"
            @select="handleBrandSelect"
          ></el-autocomplete>
        </el-col>
        <el-col :span="12">
          <el-button type="primary" @click="handleAddBrandButtonClick">添加品牌</el-button>
          <el-button type="danger" @click="handleDeleteBrandsButtonClick">批量删除</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="pageInfo.list"
        border
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column type="selection" width="60">
        </el-table-column>

        <el-table-column
          prop="code"
          label="品牌编码"
          width="140">
        </el-table-column>
        <el-table-column
          prop="name"
          label="品牌名称">
        </el-table-column>
        <el-table-column
          prop="telephone"
          label="联系电话">
        </el-table-column>
        <el-table-column
          prop="web"
          label="官网">
        </el-table-column>
        <el-table-column
          label="品牌LOGO">
          <template slot-scope="scope">
            <el-image :src="imageServer+'/'+scope.row.logo" style="width: 100px;height: 100px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="品牌描述">
        </el-table-column>
        <el-table-column
          width="100"
          align="center"
          label="启用">
          <template slot-scope="scope">
            <el-switch :active-value='1'
                       :inactive-value="0"
                       @change="handleSwitchBrandStatus(scope.row)"
                       v-model="scope.row.status"></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="modifiedTime"
          width="200"
          label="最后修改时间">
          <template slot-scope="scope">
            {{scope.row.modifiedTime}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="handleBrandDetailButtonClick(scope.row.id)">产品分类</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageNumberChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="pageSizes"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total">
      </el-pagination>
    </el-card>

    <!--品牌详情对话框-->
    <el-dialog
      title="现有产品分类"
      :visible.sync="isBrandDetailsDialogVisible"
      width="30%">
      <el-cascader
        style="width: 100%;"
        ref="cascaderRef"
        placeholder="添加分类"
        clearable
        :props="props"
        :options="prodCates"
        size="medium"
        @change="handleCateSelectionChange"
        filterable>
        <template slot-scope="scope" style="width: 100%;">
          <span v-if="testAddEnableFunction(scope.data)">{{scope.data.name}}</span>
          <el-tooltip v-else effect="dark" content="该分类已添加" placement="right-start" offset="10"
                      :enterable="false">
                    <span style="text-decoration:line-through;"
                          @click="e=>e.stopPropagation()"
                          @mouseenter="">{{scope.data.name}}</span>
          </el-tooltip>

        </template>
      </el-cascader>
      <el-tree
        style="width: 100%;margin-left: 0px;"
        default-expand-all
        :filter-node-method="filterNodeMethod"
        ref="xtreeRef"
        :props="treeProps"
        :data="allProdCates"
        :indent="32"
        node-key="id"
      >
        <template slot-scope="scope">
          <el-row style="width: 100%;">
            <el-col :span="20" style="font-size: 16px;">{{scope.data.name}}</el-col>
            <el-col v-if="scope.node.level==3" :span="4"
                    style="font-size:18px;color:#F56C6C;padding-right: 20px;">
              <i style="float:right;" class="el-icon-delete"
                 @click="handleDeleteCate3ButtonClick(scope.data.id)"></i>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </el-dialog>

    <el-dialog
      title="添加品牌"
      :visible.sync="isAddBrandDialogVisible"
      width="50%">
      <el-form>
        <el-form-item label="品牌编码:">
          <el-input v-model="newBrandFormData.code"></el-input>
        </el-form-item>
        <el-form-item label="品牌名称:">
          <el-input v-model="newBrandFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newBrandFormData.telephone"></el-input>
        </el-form-item>
        <el-form-item label="官方网站:">
          <el-input v-model="newBrandFormData.web"></el-input>
        </el-form-item>
        <el-form-item label="LOGO:">
          <el-upload
            class="upload-demo"
            drag
            :action="ossServer"
            :on-success="uploadSuccess"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="品牌描述:">
          <el-input type="textarea" v-model="newBrandFormData.description"></el-input>
        </el-form-item>
        <el-form-item label="启用:">
          <el-switch v-model="newBrandFormData.status" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="排序码:">
          <el-input v-model="newBrandFormData.orde"></el-input>
        </el-form-item>
        <el-form-item label="产品分类:">
          <el-cascader
            v-model="newBrandFormData.cates"
            :options="prodCates"
            :props="newProps"
            clearable></el-cascader>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelAddBrandButtonClick()">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAddBrandButtonClick()">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import {mapState} from 'vuex'

  import {
    readyImageServerFunction,
    readyOssServerFunction,
    readyCatesFunction,
    readyAllCatesFunction
  } from '../../funcs/commons'

  export default {
    name: "BrandManagement",
    data() {
      return {
        newProps: {
          value: 'id',
          label: 'name',
          leaf: 'isLeaf',
          expandTrigger: 'hover',
          multiple: true
        },
        options: [],

        //级联选择器的属性映射
        props: {
          value: 'id',
          label: 'name',
          leaf: 'isLeaf',
          expandTrigger: 'hover'
        },

        treeProps: {
          label: 'name',
          children: 'children'
        },
        // 分页请求时要携带的参数
        pageReqParams: {
          query: '',
          pageNum: 1,
          pageSize: 30
        },
        // 分页信息
        pageInfo: {
          pageNum: 0,
          pageSize: 0,
          total: 0,
          totalPage: 0,
          list: []
        },
        // 分页的大小常量列表
        pageSizes: [20, 30, 50, 100],

        isBrandDetailsDialogVisible: false,
        isAddBrandDialogVisible: false,
        currentRow: {},

        newBrandFormData: {
          code: 'test',
          name: 'test',
          telephone: '13677889988',
          web: 'http://gitee.com',
          logo: '',
          description: '这是测试添加的一个品牌',
          status: 1,
          orde: 0,
          cates: []
        },
        selectionInTable: []
      }
    },

    computed: {
      ...mapState({
        allProdCates: state => state.prod.allProdCates,
        prodCates: state => state.prod.prodCates,
        ossServer: state => state.prod.ossServer,
        imageServer: state => state.prod.imageServer
      })
    },


    created() {
      //准备好Oss服务器地址
      readyOssServerFunction();
      //准备好图片服务器地址
      readyImageServerFunction();
      //准备好分类数据
      readyCatesFunction();

      readyAllCatesFunction();

      this.getBrandPageFunction();
    },
    methods: {

      //上传成功
      uploadSuccess(response, file, fileList) {
        this.newBrandFormData.logo = response.data[0];
      },

      //取消添加品牌
      handleCancelAddBrandButtonClick() {
        this.isAddBrandDialogVisible = false;
      },

      //确认添加品牌
      handleConfirmAddBrandButtonClick() {
        console.log("new=" + JSON.stringify(this.newBrandFormData));
        let cates = this.newBrandFormData.cates.map(v => v[2]);
        this.newBrandFormData.cates = cates;
        this.api.__api__BrandsAdd(this.newBrandFormData)
          .then(data => {
            this.$message.success(data.message);
            this.isAddBrandDialogVisible = false;
          }).catch(error => {
          console.error(error);
        })
      },

      //记录选择行
      handleSelectionChange(selection) {
        this.selectionInTable = selection;
      },

      //批量删除品牌
      handleDeleteBrandsButtonClick() {
        this.api.__api__BrandsDelete(this.selectionInTable.map(v => v.id))
          .then(data => {
            this.$message.success(data.message);
            this.getBrandPageFunction();
          }).catch(error => {
          this.$message.error(error)
        })
      },

      // 添加品牌按钮事件
      handleAddBrandButtonClick() {
        this.isAddBrandDialogVisible = true;
      },

      // 测试是否能添加该分类
      testAddEnableFunction(cate) {
        if (this.currentRow.cates.map(value => value.id
        ).indexOf(cate.id) < 0) {
          cate.disabled = false;
          return true;
        } else {
          cate.disabled = true;
          return false;
        }
      },

      //处理选择分类后触发搜索
      handleCateSelectionChange(val) {
        if (!val || val.length == 0) return;
        let cate3Id = val[val.length - 1];
        this.api.__api__BrandsCategoryAdd(this.currentRow.id, cate3Id)
          .then(data => {
            this.api.__api__BrandsDetails(this.currentRow.id)
              .then(data1 => {
                this.currentRow = data1.data;
                var ids = this.currentRow.cates.map(value => value.id
                );
                this.$refs.xtreeRef.filter(ids);

              }).catch(error => {
              console.error(error);
            })
          }).catch(error => {
          console.error(error);
        })
      },

      // 删除品牌的一个分类
      handleDeleteCate3ButtonClick(cate3Id) {
        this.api.__api__BrandsCategoryDelete(this.currentRow.id, cate3Id)
          .then(data => {
            this.api.__api__BrandsDetails(this.currentRow.id)
              .then(data1 => {
                this.currentRow = data1.data;
                var ids = this.currentRow.cates.map(value => value.id
                );
                this.$refs.xtreeRef.filter(ids);
              }).catch(error => {
              console.error(error);
            })
          }).catch(error => {
          console.error(error);
        });
      },

      //过滤方法
      filterNodeMethod(value, data, node) {
        return value.indexOf(data.id) >= 0;
      },

      //品牌详情事件回调
      handleBrandDetailButtonClick(id) {
        this.api.__api__BrandsDetails(id)
          .then(data => {
            this.currentRow = data.data;
            this.isBrandDetailsDialogVisible = true;
            this.$nextTick(() => {
              var ids = this.currentRow.cates.map(value => value.id
              );
              this.$refs.xtreeRef.filter(ids);
            });

          }).catch(error => {
          console.error(error);
        })
      }
      ,

      //修改品牌状态
      handleSwitchBrandStatus(row) {
        this.api.__api__BrandsStatusUpdate(row.id, row.status)
          .then(data => {
            this.$message.success(data.message);
          }).catch(error => {
          console.log(error);
        })
      }
      ,

      //搜索品牌回调
      handleSearchBrandsButtonClick() {
        this.getBrandPageFunction();
      }
      ,

      //品牌选中
      handleBrandSelect(brand) {
        this.pageReqParams.query = brand.name;
      }
      ,

      //搜索品牌
      handleQuerySearchBrand(query, cb) {
        this.api.__api__BrandsByQuery(query)
          .then(data => {
            cb(data.data);
          })
      }
      ,

      //改变分页大小回调
      handlePageSizeChange(size) {
        this.pageInfo.pageSize = size;
        this.pageReqParams.pageSize = size;
        this.getBrandPageFunction();
      }
      ,

      //改变当前页回调
      handleCurrentPageNumberChange(pageNum) {
        this.pageReqParams.pageNum = pageNum;
        this.getBrandPageFunction();
      }
      ,

      //获取分页
      getBrandPageFunction() {
        this.api.__api__BrandsPage(this.pageReqParams)
          .then(data => {
            this.pageInfo = data.data;
          })
          .catch(error => {
            console.error(error);
          })
      }
    }

  }
</script>

<style scoped>
  .details {
    font-size: 16px;
    background-color: #e1f3d8;
    padding: 40px;
  }

  .label {
    display: flex;
    justify-content: right;
  }

  .details-content {
    margin-left: 5px;
    font-weight: bolder;
    text-decoration: underline;
    font-size: 18px;
  }
</style>
